<?php

namespace app\api\controller;

use app\common\controller\Api;
use app\api\model\user\UserBankAccount as UserBankAccountModel;

/**
 * 银行账户接口
 */
class Userbankaccount extends Api
{
    //protected $noNeedLogin = ['*'];
    protected $noNeedRight = ['*'];

    /**
     * 列表
     *
     */
    public function lists()
    {
        $list = UserBankAccountModel::where(['user_id'=>$this->auth->id])->select();

        $this->success('请求成功',$list);
    }

    //添加
    public function add()
    {
        $account_model = new UserBankAccountModel();

        $data = [
            'user_id'=>$this->auth->id,
            'bank_name'=>input('bank_name',''),
            'householder'=>input('householder',''),
            'account'=>input('account',''),
            'is_default'=>input('is_default',0)
        ];
        if (empty($data['bank_name']))$this->error('请输入银行');
        if (empty($data['householder']))$this->error('请输入户主');
        if (empty($data['account']))$this->error('请输入账号');

        $res = $account_model->save($data);

        $this->success('请求成功',$res);
    }

    //银行账号信息
    public function info()
    {
        $id = input('id',0);

        $info = UserBankAccountModel::get($id);

        if (!$info)$this->error('账号不存在');

        $this->success('请求成功',$info);
    }

    //删除
    public function del()
    {
        $id = input('id',0);

        $info = UserBankAccountModel::get($id);

        if (!$info)$this->error('账号不存在');

        $res = $info->delete();

        if ($res){
            $this->success('删除成功');
        } else {
            $this->error('删除失败');
        }
    }

    //编辑
    public function edit()
    {
        $id = input('id',0);

        $info = UserBankAccountModel::get($id);

        if (!$info)$this->error('账号不存在');
        $account_model = new UserBankAccountModel();
        $data = [
            'bank_name'=>input('bank_name',''),
            'householder'=>input('householder',''),
            'account'=>input('account',''),
            'is_default'=>input('is_default',0)
        ];
        if (empty($data['bank_name']))$this->error('请输入银行');
        if (empty($data['householder']))$this->error('请输入户主');
        if (empty($data['account']))$this->error('请输入账号');

        $res = $account_model->save($data,['id'=>$id]);

        $this->success('编辑成功');
    }

    //设置默认
    public function setDefault()
    {
        $id = input('id',0);
        $info = UserBankAccountModel::get($id);
        if (!$info)$this->error('账号不存在');
        UserBankAccountModel::update(['is_default'=>0],['user_id'=>$this->auth->id]);

        $info->is_default = 1;

        $info->save();

        $this->success('设置成功');
    }
}
